package com.gm.wj.util;

import org.springframework.scheduling.support.CronSequenceGenerator;

import java.util.Date;

public class CronExpressionResolver {

    public static CronExpressionResolver getInstance(String cron) {
        return new CronExpressionResolver(cron);
    }

    private CronExpressionResolver(String cron) {
        this.cron = cron;
    }

    private String cron;


    /**
     * 获得下一个符合Cron表达式的时间
     * @param time time
     * @return next time
     */
    public Date nextDateTime(Date time) {
        CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
        // currentTime为计算下次时间点的开始时间
        return cronSequenceGenerator.next(time);
    }

    /**
     * 获得下一个符合Cron表达式的时间
     * @param time time
     * @return next time
     */
    public Date nextDateTime(long time) {
        CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
        // currentTime为计算下次时间点的开始时间
        return cronSequenceGenerator.next(new Date(time));
    }

    /**
     * 获得下一个符合Cron表达式的时间
     * @param time time
     * @return next time
     */
    public long nextLongTime(Date time) {
        CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
        // currentTime为计算下次时间点的开始时间
        return cronSequenceGenerator.next(time).getTime();
    }

    /**
     * 获得下一个符合Cron表达式的时间
     * @param time time
     * @return next time
     */
    public long nextLongTime(long time) {
        CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
        // currentTime为计算下次时间点的开始时间
        return cronSequenceGenerator.next(new Date(time)).getTime();
    }

    public static final String  second="s";
    public static final String  minute="m";
    public static final String  hour="h";
    public static final String  day="d";
    public static final String  month="mon";

    /**
     * 生成Cron表达式
     *
     * @param num 数值
     * @param unit 单位：s-秒，m-分，h-小时，d-天，mon-月
     * @return
     */
    public static String timeToCron(int num, String unit) {
        switch (unit){
            case "s": return "0/" + num + " * * * * ?";
            case "m": return "0 0/" + num + " * * * ?";
            case "h": return "0 0 0/" + num + " * * ?";
            case "d": return "0 0 0 1/" + num + " * ?";
            case "mon": return "0 0 0 0 1/" + num + " ?";
            default: return "";
        }
    }

    public static void main(String[] args) {
//        3天 一次
//        String s = CronExpressionResolver.timeToCron(3, day);
        String s = CronExpressionResolver.timeToCron(3, month);
//        0 0 0 0 1/3 ?
//        定时发送websocket
        System.out.println(s);
        System.out.println(s);
    }
}
